package org.flint92.springboot.web.controller;

import org.flint92.springboot.web.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.hateoas.Resource;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;

/**
 * @author flint92
 */
@RestController
public class JsonRestController {

    @Bean
    public User currentUser() {
        return new User("json", 18);
    }

    @Autowired
    @Qualifier("currentUser")
    private User currentUser;

    @GetMapping(value = "/json/user",
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Resource<User> user() {
        User user = currentUser;
        return new Resource<>(user,
                linkTo(methodOn(JsonRestController.class).setUserName(user.getName())).withSelfRel());
    }

    @GetMapping(value = "/json/user/set/name",
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Resource<User> setUserName(@RequestParam String name) {
        User user = currentUser;
        user.setName(name);

        return new Resource<>(user,
                linkTo(methodOn(JsonRestController.class).user()).withSelfRel());
    }


}
